<template>
<div id="">
  <van-sticky v-if="isShowSearch" class="search">
    <div class="searchItem">
      <van-row gutter="12">
        <van-col :span="12">
          <van-field readonly clickable name="picker" :value="showParams.serveCategoryName" placeholder="请选择服务类别" @click="showPicker = true" />
          <van-popup v-model="showPicker" position="bottom">
            <van-picker show-toolbar :columns="columns" @confirm="confirmTarget" @cancel="showPicker = false" title="服务类别" value-key="name" />
          </van-popup>
        </van-col>
        <van-col :span="12">
          <van-field v-model="searchFilter.keywords" placeholder="请输入活动名称" right-icon="search" @click-right-icon="handleQuery()" />
        </van-col>
      </van-row>
    </div>
    <div class="searchItem">
      <van-field readonly clickable name="calendar" :value="showParams.dateRange" placeholder="请选择活动日期" @click="showCalendar = true" />
      <van-calendar v-model="showCalendar" type="range" color="#EB4446" row-height="45" :min-date="new Date('2022-01-01')" :max-date="new Date('2023-12-31')" @confirm="onConfirm" ref="myCalendar">
        <div slot="footer" class="canlendarStyle text-right">
          <van-button type="danger" @click="clearDate()">清空</van-button>
          <van-button type="danger" class="ml6" @click="confirmDate()">确定</van-button>
        </div>
      </van-calendar>
    </div>
    <van-tabs v-model="activeTab" v-if="tabList && tabList.length >0" @change="tabChange()">
      <van-tab name="-1">
        <div slot="title">
          <p class="top">全部</p>
          <p class="num">{{getTotal()}}</p>
        </div>
      </van-tab>
      <van-tab v-for="item in tabList" :name="item.status">
        <div slot="title">
          <p class="top">{{item.statusName}}</p>
          <p class="num">{{item.total}}</p>
        </div>
      </van-tab>
    </van-tabs>
  </van-sticky>
  <div v-if="!isShowSearch">
    <van-tabs v-model="activeTab" v-if="tabList && tabList.length >0" @change="tabChange()">
      <van-tab name="-1">
        <div slot="title">
          <p class="top">全部</p>
          <p class="num">{{getTotal()}}</p>
        </div>
      </van-tab>
      <van-tab v-for="item in tabList" :name="item.status">
        <div slot="title">
          <p class="top">{{item.statusName}}</p>
          <p class="num">{{item.total}}</p>
        </div>
      </van-tab>
    </van-tabs>
  </div>
  <div :class="isShowSearch ? 'contentHeight' : ''" class="contents">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :offset="10">
        <van-cell v-for="(item,index) in dataList" :key="index" class="dateItem" @click="handleDetail(item)" clickable>
          <!-- <img :src="setStatusImg(item)" alt="" class="actiStatus"> -->
          <span :class="setStatusColor(item)" class="statusTagSize">
            <span :class="setStatusBorderColor(item)">
              {{item.statusStr}}
            </span>
          </span>
          <div class="card">
            <van-row>
              <van-col :span="5">
                <div class="activityImg" :style="{background: 'url(' + setPreviewUrl(item) + ')', backgroundSize:'cover', backgroundPosition: 'center'}"></div>
                <!-- <img :src="setPreviewUrl(item)" alt="" class="activityImg"> -->
              </van-col>
              <van-col :span="19">
                <p style="font-weight:bolder" class="textEllipsis">{{item.activityName}}</p>
                <p class="remark textEllipsis">
                  <van-icon name="location-o" class="mr4" />{{item.address}}
                </p>
                <p class="remark textEllipsis">
                  <van-icon name="cluster-o" class="mr4" />{{item.groundName}}
                </p>
              </van-col>
            </van-row>
          </div>
          <p class="distAlign mt4" style="color:#666666;">
            <span>服务类别：{{item.serveCategoryStr}}</span>
          </p>
          <p style="color:#666666" class="textEllipsis">活动时间：{{item.startDate}} 至 {{item.endDate}}</p>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</div>
</template>
<script>
export default {
  name: "",
  props: {
    isShowSearch: {
      type: Boolean,
      default: true,
    },
    groundId: {
      type: String,
      default: ""
    },
    projectId: {
      type: String,
      default: ""
    },
  },
  data() {
    return {
      dataList: [],
      loading: false,
      finished: false,
      refreshing: false,
      error: false,
      showType: 'list',
      queryParams: {
        pageNum: 0,
        pageSize: 10
      },
      showCalendar: false,
      showPicker: false,
      columns: [],
      activeTab: "-1",
      tabList: [],
      showParams: {
        dateRange: "",
        serveCategoryName: '',
      },
      topSearchTotalData: [],
      defaultImg: require('../../assets/images/default_activity.jpg'),
      ingImg: require('../../assets/images/ing.png'),
      endImg: require('../../assets/images/end.png'),
      notImg: require('../../assets/images/not.png'),
      searchFilter: {}
    }
  },
  computed: {
    statusFilters() {
      return function(val) {
        let arr = this.tabList.filter(x => x.status.toString() == val.status);
        if (arr.length > 0) {
          return arr[0].statusName
        } else {
          return ""
        }
      }
    }
  },
  created() {
    this.init();
    this.getCount()
  },
  methods: {
    getCount() {
      let me = this;
      me.$api.getCountByActiStatus({
        dto: {
          groundId: me.groundId || me.$route.query.groundId,
          projectId: me.projectId || me.$route.query.projectId,
          dateRange: me.searchFilter.dateRange,
          keywords: me.searchFilter.keywords,
          serverTarget: me.searchFilter.serverTarget
        }
      }).then(res => {
        me.tabList = res;
      })
    },
    init() {
      let me = this;
      me.columns = [];
      me.$api.getDicByCode({
        params: {
          dictCode: "ServerCategory"
        }
      }).then((res) => {
        let arr = [{
          id: '-1',
          name: '全部'
        }];
        me.columns = arr.concat(res);
      })
    },
    getTotal() {
      let me = this;
      let total = 0;
      if (me.tabList.length > 0) {
        total = me.$utils.funCalc(me.tabList.map(x => x.total), 1, 0)
      } else {
        total = 0
      }
      return total
    },
    onRefresh() {
      this.dataList = []
      this.queryParams.pageNum = 0;
      this.finished = false;
      this.onLoad();
    },
    onLoad() {
      let me = this;
      me.loading = true;
      me.queryParams.pageNum++;
      me.getActivities()
    },
    getActivities() {
      let me = this;
      let queryData = {};
      me.searchFilter.groundId = me.groundId || me.$route.query.groundId
      me.searchFilter.projectId = me.projectId || me.$route.query.projectId
      queryData = {
        pageParam: me.queryParams,
        dto: me.searchFilter
      }
      me.$api.getActivitiesList(queryData).then(res => {
        if (res.dataList.length == 0) { // 本次没有数据
          me.dataList = [];
          //me.$toast('暂无数据');
          me.refreshing = false;
          me.finished = true;
        } else { // 本次有数据
          me.dataList = [
            ...me.dataList,
            ...res.dataList
          ];
          me.loading = false;
          me.refreshing = false;
          me.dataList.length >= res.totalCount ? (me.finished = true) : ""
        }
      })
    },
    handleQuery() {
      this.onRefresh()
      this.getCount()
    },
    formatDate(date) {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    onConfirm(event) {
      const [start, end] = event;
      let startDate = this.formatDate(start) + ' 00:00:00';
      let endDate = this.formatDate(end) + ' 00:00:00';
      this.showCalendar = false;
      this.searchFilter.dateRange = [startDate, endDate]
      this.$set(this.showParams, "dateRange", `${this.formatDate(start)} 至 ${this.formatDate(end)}`)
    },
    clearDate() {
      this.showCalendar = false;
      this.searchFilter.dateRange = []
      this.$set(this.showParams, "dateRange", "")
      this.onRefresh()
      this.getCount()
    },
    confirmDate() {
      this.$refs.myCalendar.onConfirm();
      this.onRefresh()
      this.getCount()
    },
    confirmTarget(val) {
      let me = this;
      if (val.id == '-1') {
        me.$set(me.searchFilter, "serveCategory", "")
        me.$set(me.showParams, "serveCategoryName", "")
      } else {
        me.$set(me.searchFilter, "serveCategory", val.id)
        me.$set(me.showParams, "serveCategoryName", val.name)
      }
      me.showPicker = false;
      me.onRefresh()
      me.getCount()
    },
    tabChange() {
      let me = this;
      me.$set(me.searchFilter, "status", me.activeTab == '-1' ? "" : me.activeTab)
      me.onRefresh()
      me.getCount()
    },
    setStatusColor(item) {
      let className = "";
      if (item.status == 5) {
        className = "color5"
      } else if (item.status == 10) {
        className = "color10"
      } else {
        className = "color20"
      }
      return className
    },
    setStatusBorderColor(item){
      let className = "";
      if (item.status == 5) {
        className = "borderColor5"
      } else if (item.status == 10) {
        className = "borderColor10"
      } else {
        className = "borderColor20"
      }
      return className
    },
    handleDetail(item) {
      this.$router.push({
        path: '/activities/detail',
        query: {
          id: item.activityId,
          title: item.activityName
        }
      })
    },
    setPreviewUrl(val) {
      if (val.coverImage && val.coverImage.length > 0) {
        // return this.defaultImg
        return process.env.VUE_APP_BASE_URL + 'admin/upms/file/download?filename=' + val.coverImage[0]
      } else {
        return this.defaultImg
      }
    },
    setStatusImg(item) {
      let imgUrl = "";
      if (item.status == 5) {
        imgUrl = this.notImg
      } else if (item.status == 10) {
        imgUrl = this.ingImg
      } else {
        imgUrl = this.endImg
      }
      return imgUrl
    }
  }
}
</script>
<style lang="scss" scoped>
.contents {
    padding: 0.2rem;
    background-color: #f5f5f5;
}
.contentHeight {
    height: calc(100vh - 5rem);
    overflow-y: scroll;
}
.flexItem {
    display: flex;
}
.canlendarStyle {
    padding: 0.2rem 0;
}
.activityImg {
    display: inline-block;
    width: 1.6rem;
    vertical-align: middle;
    height: 1.5rem;
}
</style>
